//模块配置信息
require.config({
	//baseUrl: "./",
	paths: {
		//工具模块
		'less': 'tools/less.min',
		'jquery': 'tools/jquery.min',
		'bootstrap': 'tools/bootstrap.min',
		'handlebars': 'tools/handlebars',

		//配置模块
		'config': './config',
		"appConfig":"./appConfig",
		'showBigImg':'modules/showBigImg',
		'top_bar': 'modules/top_bar',
		'problem': 'modules/problem',
		'ask': 'modules/ask',
		'modal_template': 'modules/modal_template',
		'cookie': 'modules/cookie',
		'check_log': 'modules/check_log',
		'login': 'modules/login',
		'other_log': 'modules/login',
		'reg': 'modules/reg',
		'user': 'modules/user',
		'userProblem':'modules/userProblem',
		'uploadFile':'modules/uploadFile'　　
	},
	skim: {  //配置依赖关系与接口
		"bootstrap": {	// bootstrap依赖jquery库
			deps: ['jquery'],
			exports: 'bootstrap'
		},
		"handlebars": {
			exports: 'Handlebars'
		},
		"user": {
			deps: ['modal_template']
		}
	}
});
/************************************header***************************************/
//加载顶栏top_bar模块
require(['top_bar'], function(top_bar){
	top_bar();
});
/************************************content***************************************/
require(['jquery','handlebars','userProblem','cookie','config','uploadFile','showBigImg','less'], function ($,Handlebars,userProblem,cookie,config,uploadFile,showBigImg){
var avatarUrl,userId;
$(document).ready(function(){
	require(['bootstrap']);//为了绑定登陆注册按钮弹窗事件
	userId = cookie.getCookie('userId');
	console.log(userId);
	if(!userId){
		alert("请先登录");
	}else{

		fetchUserData(userId);
	}

	
});
var imgFiles=[];
//input获取文件
function getFiles(e) {
	// isUpload = false;
	e = e || window.event;
	//获取file input中的图片信息列表
	var files = e.target.files,
		//验证是否是图片文件的正则
		reg = /image\/.*/i;
	fileType = files[0].type,
	fileName = files[0].name; //如果选择了多张图片，只上传第一张
	console.log(files);

	if (!reg.test(fileType)) {
		alert("你选择的" + fileName + "文件不是图片");
		return;
	} else {
		imgFiles.push(files[0]);
		$(".selectedFileName").text(fileName);
	}
}
function fetchUserData(userId){
	$.ajax({
		url:config.api.getUserInfo[0].replace(/\<\w+\>/,userId),
		type:config.api.getUserInfo[1],
		success:function(d){
			avatarUrl=d.user.avatarUrl||"image/emptyAvatar.jpg";
			handlebarsRender("#userInfo-template",".container",d);
			$(".tabs").delegate("li","click",function(){
				var ref=$(this).data("ref");
				$(".tab-nav").removeClass("active");
				$(this).addClass("active");
				$(".tabs-body").removeClass("show").parent().find(".tabs-body[data-ref="+ref+"]").addClass("show");
			});//绑定事件

		//截去头像过长部分
			var colWidth = $('.image-info img').width();
			$('.image-info').css('height', colWidth);

			//更改浏览器窗口大小时
			$(window).resize(function(){
				var colWidth = $('.image-info img').width();
				$('.image-info').css('height', colWidth);
			});

			//获取内容数据
			var date = new Date();
			var timestamp = date.getTime();
			userProblem.getProblemList(0, 20, timestamp, userId,avatarUrl);
			userProblem.getComments(0, 20, timestamp, userId,avatarUrl);
			getWorks();
		}
	});
}
function handlebarsRender(tplSelector,destSelector,data){
	//用jquery获取模板
	var source   = $(tplSelector).html();
	//预编译模板
	var template = Handlebars.compile(source);
	//匹配json内容
	var html = template(data);
	//输入模板
	$(destSelector).html(html);
}
Handlebars.registerHelper("firstInRow",function(index,options){
	if(index%4==0){
		return options.fn(this);
	}else{
		return options.inverse(this);
	}
});//注册一个用于判断是否是某行的第一个item的helper

function commentTo(option){
	if(!option.content||!option.problemId){
		return;
	}else{
		$.ajax({
			url:"msq/api/user/"+userId+"/comment",
			type:"post",
			data:option,
			success:function(d){
				console.log("new comment",d);
			}
		});
	}
}
function answerTo(option){
	if(!option.content||!option.problemId){
		return;
	}else{
		$.ajax({
			url:appConfig.host+"/api/user/"+testID2+"/answer",
			type:"post",
			data:option,
			success:function(d){
				console.log("post new answer",d);
			}
		});
	}
}
function getComments(userId){
	$.ajax({
		url:"msq/api/user/"+userId+"/comments",
		type:"get",
		success:function(d){
			console.log(d);
           handlebarsRender("#comments","#myComment",d);
           var $tabNum=$(".tabs").find("li[data-ref=#myComment]>span");
           $tabNum.text(d.comments.length);
		}
	});
	
}
function getProblems(userId){
	$.ajax({
		url:appConfig.host+"/api/user/"+userId+"/problems",
		type:"get",
		success:function(d){
			console.log(d);

			handlebarsRender("#qustionRow","#myQuestion",d);
			var $tabNum=$(".tabs").find("li[data-ref=#myQuestion]>span");
			$tabNum.text(d.problems.length);
			$(".comment").hide();
			$(".operation_btns").delegate(".toggleComment","click",function(){
				var $toggleCommentText=$(this).find(".toggleCommentText");
				if($toggleCommentText.text()=="收起评论"){
					$toggleCommentText.text("展开评论");
				}else {
					$toggleCommentText.text("收起评论");
				}
				$(this).parent().next().toggle();
			});
		}
	});
	
}
//获取用户的作品
function getWorks(){
	$.ajax({
		url:config.api.getAllWorks[0].replace(/\<\w+\>/,userId),
		type:config.api.getAllWorks[1],
		success:function(d){
			console.log(d);
			handlebarsRender("#works","#myWork",d);
			//将图片设置为居中
			var w=$("#myWork").width()*0.24;
			$(".pic_row_item.myWorkPic").css({
				lineHeight:w+"px"
			}).find(".workPic").css({
				maxHeight:w+"px",
				maxWidth:w+"px"
			});
			//窗口大小变化时
			$(window).resize(function(){
				var w=$("#myWork").width()*0.24;
				$(".pic_row_item.myWorkPic").css({
					lineHeight:w+"px"
				}).find(".workPic").css({
					maxHeight:w+"px",
					maxWidth:w+"px"
				});
			});
			$(".workPic").on("click",function(){
				var src=$(this).attr("src");
				showBigImg(src);
			});//点击看大图
			$("#uploadWorkInput").on("change",getFiles);
			$("#uploadWorkBtn").on("click",function(){
				if(imgFiles.length>0){
					uploadFile.uploadImgFiles(imgFiles,addWork);
				}else{
					$("#uploadWorkInput").click();
				}
				
			});
			$("#myWork").on("click",".myWorkPic",function(){
				if(editing){
					var $this=$(this);
					var url=$this.find("img").attr("src");
					$this.toggleClass("selectedWork");
					if($this.hasClass("selectedWork")){
						worksToDelete.push(url);
					}else{
						var index=worksToDelete.indexOf(url);
						if(index>-1){
							worksToDelete.splice(index,1);
						}
						
					}
					
				}
			});
			$("#editWorkBtn").on("click",function(){
				if(!editing){
					editing=true;
					$(this).text("确定");
					$(".crossIcon").removeClass("hide");
				}else{
					deleteWorks();
					editing=false;
					$(this).text("编辑");
					$(".crossIcon").addClass("hide");
				}
			});
		},
		error:function(){
			alert("获取作品失败");
		}
	});
}
//添加作品
function addWork(urls){
	$.ajax({
		url:config.api.addWorks[0].replace(/\<\w+\>/,userId),
		type:config.api.addWorks[1],
		data:{
			imageUrl :urls[0]
		},
		success:function(d){
			fetchUserData(userId);
			//alert("添加作品成功");
		},
		error:function(){
			fetchUserData(userId);
			//alert("添加作品失败");
		}
	});
}
var editing=false;
var worksToDelete=[];
var feedBack={
	success:0,
	fail:0,
	total:0,
	complete:function(){
		return (this.success+this.fail==this.total);
	},
	reset:function(){
		this.success=0;
		this.fail=0;
		this.total=0;
	}
};
function deleteWorks(){
	feedBack.reset();
	feedBack.total=worksToDelete.length;
	for(var i=0,len=worksToDelete.length;i<len;i++){
		deleteWork(worksToDelete[i]);
	}
}
function deleteWork(url){
	$.ajax({
		url:config.api.deleteWork[0].replace(/\<\w+\>/,userId),
		type:config.api.deleteWork[1],
		data:{
			imageUrl :url
		},
		success:function(){
			feedBack.success++;
			if(feedBack.complete()){
				// alert("删除完成,成功个数"+feedBack.success+"失败个数:"+feedBack.fail);
				feedBack.reset();
				fetchUserData(userId);
			}
		},
		error:function(){
			feedBack.fail++;
			if(feedBack.complete()){
				// alert("删除完成,成功个数"+feedBack.success+"失败个数:"+feedBack.fail);
				feedBack.reset();
				fetchUserData(userId);
			}
		}
	});
}
});
